#include<iostream>
#include<string>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

void CutStr(const string& target, string& out1, string& out2,const string div) {
     size_t pos = target.find(div);
     out1 = target.substr(0, pos);
     out2 = target.substr(pos + div.size());
}

int main() {
    
    cerr << "---------------------------------" << endl;
    string method = getenv("METHOD");
    cerr << "method = "<< method << endl;

    int x, y;

    if (method == "GET") {
       cerr << "Get DATA.." << endl;
       cerr <<"************"<< endl;
       string target = getenv("INPUT"); 
       std::cerr << "INPUT=" << target << endl;
       string out1, out2;
       string name1, value1;
       string name2, value2;
       CutStr(target, out1, out2, "&");
       CutStr(out1, name1, value1, "=");
       CutStr(out2, name2, value2, "=");
       x = atoi(value1.c_str());
       y = atoi(value2.c_str());
    }
    else if (method == "POST") {
       size_t length= atoi(getenv("CONTENT_LENGTH")); 
       size_t cnt = 0; 
       size_t s = 0; 
       char buf[1024];
       while (cnt < length && (s = read(0, buf + cnt, length - cnt)) > 0) {
          cnt += s;
       }
       buf[cnt] = '\0';
       cerr << buf << endl;
       cout << buf << endl;
    }
    cerr << "x = " << x << endl;
    cerr << "y = " << y << endl;
    /*以html方式写回*/
    //可能向进行某种计算(计算，搜索，登陆等)，想进行某种存储(注册)
    std::cout << "<html>";
    std::cout << "<head><meta charset=\"utf-8\"></head>";
    std::cout << "<body>";
    std::cout << "<h3> " << x << " + " << y << " = "<< x + y << "</h3>";
    std::cout << "<h3> " << x << " - " << y << " = "<< x - y << "</h3>";
    std::cout << "<h3> " << x << " * " << y << " = "<< x * y << "</h3>";
    std::cout << "<h3> " << x << " / " << y << " = "<< x / y << "</h3>";
    std::cout << "</body>";
    std::cout << "</html>";
    return 0;
}
